/*
 * Author: TalkLittle
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

#include "MRS.h"

void usage() {
    printf("Usage:\n"
    "extract_mrs <inputfile> <start_offset>\n");
}

int main(int argc, char **argv) {
    unsigned char *output, *bmpheader;
    unsigned char mrsheader[MRS_HEADER_LEN];
    int outheadersize;
    int16_t width, height;
    char *outfile = NULL;
    FILE *infp, *outfp, *logfp;
    int c, i;
    extern char *optarg;
    extern int optind, opterr, optopt;

    if (argc < 3) {
        usage();
        exit(1);
    }
    while ((c = getopt(argc, argv, "o")) != -1) {
        switch (c) {
        case 'o':
            outfile = strdup(optarg);
            break;
        default:
            fprintf(stderr, "ERROR: Unrecognized command line arg %c\n", c);
            exit(1);
        }
    }
    logfp = stderr;

    /* Extract header data */
    infp = fopen(argv[1], "rb");
    output = MRS_extract_filename(infp, argv[2], &width, &height, mrsheader);
    fclose(infp);

    /* Get BMP header */
    bmpheader = MRS_to_bmp_header(mrsheader, width * height, &outheadersize);

    /* Write the results */
    if (outfile)
        outfp = fopen(outfile, "wb");
    else
        outfp = stdout;
    //bytes_written += fwrite(bmpheader, 1, outheadersize, outfp);
    fwrite(bmpheader, 1, outheadersize, outfp);
    /* Scanlines start from bottom */
    for (i = height - 1; i >= 0; i--) {
        //bytes_written += fwrite(&output[i*width], 1, width, outfp);
        fwrite(&output[i*width], 1, width, outfp);
    }
    if (outfile)
        fclose(outfp);

    free(outfile);
    free(output);
    free(bmpheader);

    //fprintf(logfp, "Read %d bytes\n", bytes_read);
    //fprintf(logfp, "Wrote %d bytes\n", bytes_written);

    return 0;
}
